<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------
if(!function_exists('cat_subTree')){
/**
 * ���ָ�������µ��ӷ��������
 *
 * @access  public
 * @param   int     $cat_id     �����ID
 * @param   int     $res   ��ǰѡ�з����ID
 * @param   int     $is_show_all ���Ϊtrue��ʾ���з��࣬���Ϊfalse���ز��ɼ���ࡣ
 * @return  mix
 */
function cat_subTree($res,$cat_id,$is_show_all=false){
	static $trees;
	if(isset($trees[$cat_id])) return $trees[$cat_id];
	$result = array();
	foreach($res as $_cat){
		if($_cat['parent_id']==$cat_id){
			if(!$is_show_all){
				if($_cat['is_show']!=1) continue;
			}
			$result[] = $_cat;
		}
	}
	$trees[$cat_id] = $result;
	return $result;
}
}

if(!function_exists('getByCond')){
function getByCond($res,$cond){
	foreach($cond as $feild=>$value){
		$rs = array();
		foreach($res as $key=>$val){
			if($val[$feild]==$value)$rs[] = $val;
		}
		$res = $rs;
	}
	return $res;
}
}

/**
 * ��ɱ༭��
 * @param   string  input_name  ��������
 * @param   string  input_value �����ֵ
 */
if(!function_exists('get_html_editor')){
function get_html_editor($input_name, $input_value = '',$param=array())
{
	include_once(dirname(BASEPATH).'/fckeditor/fckeditor.php');
    $editor = new FCKeditor($input_name);
    $editor->BasePath   = '../fckeditor/';
    $editor->ToolbarSet = 'Normal';
    $editor->Width      = '100%';
    $editor->Height     = '320';
    $editor->Value      = $input_value;
    $FCKeditor = $editor->CreateHtml();
    return $FCKeditor;
}
}

/**
 * ���ָ�������µ��ӷ��������
 *
 * @access  public
 * @param   int     $cat_id     �����ID
 * @param   int     $selected   ��ǰѡ�з����ID
 * @param   boolean $re_type    ���ص�����: ֵΪ��ʱ���������б�,���򷵻�����
 * @param   int     $level      �޶����صļ���Ϊ0ʱ�������м���
 * @param   int     $is_show_all ���Ϊtrue��ʾ���з��࣬���Ϊfalse���ز��ɼ���ࡣ
 * @return  mix
 */
if(!function_exists('cat_list')){
function cat_list($res,$cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true)
{
    /*$fields = array('id'=>'id','name'=>'cat_name','parents_id'=>'parents_id','is_show'=>'is_show');

	if(isset($res['fields'])){
		$fields = $res['fields'];
		$res = $res['resultset'];
	}*/
	if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }
	$options = $res;
    $children_level = 99999; //�����������Ľ���ɾ��
    if ($is_show_all == false)
    {
        foreach ($options as $key => $val)
        {
            if ($val['level'] > $children_level)
            {
                unset($options[$key]);
            }
            else
            {
                if (isset($val['is_show']) && $val['is_show'] == 0)
                {
                    unset($options[$key]);
                    if ($children_level > $val['level'])
                    {
                        $children_level = $val['level']; //���һ�£������ӷ���Ҳ��ɾ��
                    }
                }
                else
                {
                    $children_level = 99999; //�ָ���ʼֵ
                }
            }
        }
    }

    /* ��ȡ��ָ������������ */
    if ($level > 0)
    {
        if ($cat_id == 0)
        {
            $end_level = $level;
        }
        else
        {
            $first_item = reset($options); // ��ȡ��һ��Ԫ��
            $end_level  = $first_item['level'] + $level;
        }

        /* ����levelС��end_level�Ĳ��� */
        foreach ($options AS $key => $val)
        {
            if ($val['level'] >= $end_level)
            {
                unset($options[$key]);
            }
        }
    }

    if ($re_type == true)
    {
        $select = '';
		//֧��multiple��ѡ��
		$function = 'is_str_cmp';
		if(is_array($selected)) $function = "in_array";
        foreach ($options AS $var)
        {
            $select .= '<option class="opt_lavel_'.$var['level'].'" value="' . $var['id'] . '" ';
            $select .= ($function($var['id'],$selected)) ? "selected='ture'" : '';
            $select .= '>';
            if ($var['level'] > 0)
            {
                $select .= str_repeat('&nbsp;', $var['level'] * 4);
            }
            $select .= htmlspecialchars($var['name'], ENT_QUOTES) . '</option>';
        }
        return $select;
    }
    return $options;
}

function is_str_cmp($val,$val2){
	if($val==$val2) return true;
	return false;
}
}

/**
 * ���˺��������з��࣬����һ����������������
 *
 * @access  private
 * @param   int     $cat_id     �ϼ�����ID
 * @param   array   $arr        �������з��������
 * @param   int     $level      ����
 * @return  void
 */
if(!function_exists('cat_options')){
function cat_options($spec_cat_id, $arr)
{
    static $cat_options = array();

	if(empty($arr)) return array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }
    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        while (!empty($arr))
        {
            foreach ($arr AS $key => $value)
            {
                $cat_id = $value['id'];
                if ($level == 0 && $last_cat_id == 0)
                {
                    if ($value['parent_id'] > 0)
                    {
                        break;
                    }

                    $options[$cat_id]          = $value;
                    $options[$cat_id]['level'] = $level;
                    $options[$cat_id]['id']    = $cat_id;
                    $options[$cat_id]['name']  = $value['name'];
                    unset($arr[$key]);

                    if ($value['has_children'] == 0)
                    {
                        continue;
                    }
                    $last_cat_id  = $cat_id;
                    $cat_id_array = array($cat_id);
                    $level_array[$last_cat_id] = ++$level;
                    continue;
                }

                if ($value['parent_id'] == $last_cat_id)
                {
                    $options[$cat_id]          = $value;
                    $options[$cat_id]['level'] = $level;
                    $options[$cat_id]['id']    = $cat_id;
                    $options[$cat_id]['name']  = $value['name'];
                    unset($arr[$key]);

                    if ($value['has_children'] > 0)
                    {
                        if (end($cat_id_array) != $last_cat_id)
                        {
                            $cat_id_array[] = $last_cat_id;
                        }
                        $last_cat_id    = $cat_id;
                        $cat_id_array[] = $cat_id;
                        $level_array[$last_cat_id] = ++$level;
                    }
                }
                elseif ($value['parent_id'] > $last_cat_id)
                {
                    break;
                }
            }

            $count = count($cat_id_array);
            if ($count > 1)
            {
                $last_cat_id = array_pop($cat_id_array);
            }
            elseif ($count == 1)
            {
                if ($last_cat_id != end($cat_id_array))
                {
                    $last_cat_id = end($cat_id_array);
                }
                else
                {
                    $level = 0;
                    $last_cat_id = 0;
                    $cat_id_array = array();
                    continue;
                }
            }

            if ($last_cat_id && isset($level_array[$last_cat_id]))
            {
                $level = $level_array[$last_cat_id];
            }
            else
            {
                $level = 0;
            }
        }
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }

    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}
}

/**
 *	UTF-8��ȡ�ַ�
 *	@author	kokko<kokko313@gmail.com>
 *	@version 1.0 2007-8-30
 *	@param $string
 *	@param $length
 *	@param $etc
 *	@param $count_words
 *	@return String
 */
if(!function_exists('do_substr')){
function do_substr( $string,$length = 80,$etc='...',$count_words = true ) {
	mb_internal_encoding("UTF-8");
	if ($length == 0)return '';
	if ( strlen( $string ) <= $length ) return $string;
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info); 
   if( $count_words ){
		$j = 0;
		for($i=0; $i<count($info[0]); $i++) {
			$wordscut .= $info[0][$i];
			if( ord( $info[0][$i] ) >=128 ){
				$j = $j+2;
			}else{
				$j = $j + 1;
			}
			if ($j >= $length ) {
					return $wordscut.$etc;
			}
		}
		return join('', $info[0]);
   }
	return join("",array_slice( $info[0],0,$length ) ).$etc;
}
}

/**
 * �����ļ��У�����ʽ�����ļ��У�
 * @author null
 * @version 1.0 2007��10��8��
 * @param string $dir
 * @param string $mode
 * @return void;
 */
if(!function_exists('do_mkdirs')){
function do_mkdirs($dir, $mode = 0777) {
    $stack = array(basename($dir));
    $path = null;
    while ( ($d = dirname($dir) ) ) {
        if ( !is_dir($d) ) {
            $stack[] = basename($d);
            $dir = $d;
        } else {
            $path = $d;
            break;
        }
    }

    if ( ( $path = realpath($path) ) === false )
    return false;

    $created = array();
    for ( $n = count($stack) - 1; $n >= 0; $n-- ) {
        $s = $path . '/'. $stack[$n];
        if ( !mkdir($s, $mode) ) {
            for ( $m = count($created) - 1; $m >= 0; $m-- )
            rmdir($created[$m]);
            return false;
        }
        $created[] = $s;
        $path = $s;
    }
    return true;
}//end function
}

/**
 * ɾ���Ŀ¼�µ������ļ����ļ���
 * @author kokko<kokko313@gamil.com>
 * @param string $dir:Ŀ¼ ����c:\www1\ Ϊ���·?
 * @param string $tag:true:ͬʱɾ���Ŀ¼��false:����ɾ���Ŀ¼�µ��ļ�����Ŀ?
 * @return bool
 */
if(!function_exists('do_rmdirs')){
function do_rmdirs( $dir, $tag = false ) {
	//���庯���������򣬱�����ɾ�������վ
	$parent = DOCUROOT."/data/";
		
	//���������ɾ��dataĿ¼�µ��ļ�;
	$self = substr($dir,0,strlen($parent));	
	if($self != $parent)	return false;
	
	//data��ĵ�һ��Ŀ¼�������
	$first=substr($dir,strlen($parent));
	$pos= strpos($first ,"/",0 );
	if($pos==0)	return false;
	
	//ֻ�ܶ�data��ĵڶ���Ŀ¼ִ��ɾ�����
	$second= substr( $first,$pos+1 );
	$checkpos = strpos($second,"/",0 );
	if( $checkpos==0 ) return false;
	
	if( $handle = @opendir( $dir ) ){
		while( ( $file = @readdir( $handle ) ) !== false ){
			if( $file != "." && $file != ".." ){
				$filepath = $dir."/".$file;
				if( is_file( $filepath ) ){
					@unlink( $filepath );
				}elseif( is_dir( $filepath ) ){
					func_rmDirs( $filepath,true );
				}
			}
		}
		closedir( $handle );
	}

	if( $tag ){
		@rmdir( $dir );
	}
	return true;
}//end function
}


/**
 * �ַ�����Լ����ܺ���
 *
 * @param string $string	ԭ�Ļ�������
 * @param string $operation	����(ENCODE | DECODE), Ĭ��Ϊ DECODE
 * @param string $key		��Կ
 * @param int $expiry		������Ч��, ����ʱ����Ч�� ��λ �룬0 Ϊ������Ч
 * @return string		������ ԭ�Ļ��� ���� base64_encode ����������
 *
 * @example
 *
 * 	$a = authcode('abc', 'ENCODE', 'key');
 * 	$b = authcode($a, 'DECODE', 'key');  // $b(abc)
 *
 * 	$a = authcode('abc', 'ENCODE', 'key', 3600);
 * 	$b = authcode('abc', 'DECODE', 'key'); // ��һ��Сʱ�ڣ�$b(abc)������ $b Ϊ��
 */
if(!function_exists('do_authcode')){
function do_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;	//note �����Կ���� ȡֵ 0-32;
				//note ���������Կ���������������κι��ɣ�������ԭ�ĺ���Կ��ȫ��ͬ�����ܽ��Ҳ��ÿ�β�ͬ�������ƽ��Ѷȡ�
				//note ȡֵԽ�����ı䶯����Խ�����ı仯 = 16 �� $ckey_length �η�
				//note ����ֵΪ 0 ʱ���򲻲��������Կ

	$key = md5($key ? $key : UC_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}
}

if(!function_exists('do_post')){
function do_post($url,$data,$cookie=null){
    if (is_array($data)) 
    { 
        ksort($data);
        $data = http_build_query($data);
    }
    if(is_array($cookie)) $cookie = http_build_query($cookie);
 
    $opts = array( 
      'http'=>array( 
        'method'=>"POST", 
        'header'=>"Content-type: application/x-www-form-urlencoded\r\n". 
                  "Content-length:".strlen($data)."\r\n" .  
                  "Cookie: {$cookie}\r\n" .  
                  "\r\n", 
        'content' => $data, 
      ) 
    ); 
    $cxContext = stream_context_create($opts); 
    $sFile = file_get_contents($url, false, $cxContext); 
    return $sFile;
}
}

function get_img_url($img,$path=null){
	//���url���о��·��
	if(strstr($img,'http://')||strpos($img, '/')===0){
		return $img;
	}
	return base_url().$path.'/'.$img;
}

/**
 *	UTF-8��ȡ�ַ�
 *	@author	kokko<kokko313@gmail.com>
 *	@version 1.0 2007-8-30
 *	@param $string
 *	@param $length
 *	@param $etc
 *	@param $count_words
 *	@return String
 */
function do_substr( $string,$length = 80,$etc='...',$count_words = true ) {
	mb_internal_encoding("UTF-8");
	if ($length == 0)return '';
	if ( strlen( $string ) <= $length ) return $string;
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info); 
   if( $count_words ){
		$j = 0;
		for($i=0; $i<count($info[0]); $i++) {
			$wordscut .= $info[0][$i];
			if( ord( $info[0][$i] ) >=128 ){
				$j = $j+2;
			}else{
				$j = $j + 1;
			}
			if ($j >= $length ) {
					return $wordscut.$etc;
			}
		}
		return join('', $info[0]);
   }
	return join("",array_slice( $info[0],0,$length ) ).$etc;
}

function get_remote_ip(){
	$onlineip = "unknown";
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	if($onlineip=='unknown'||$onlineip=='127.0.0.1') return null;
	return $onlineip;
}

function dir_path($path) {
	$path = str_replace('\\', '/', $path);
	if(substr($path, -1) != '/') $path = $path.'/';
	return $path;
}

function dir_list($path, $exts = '', $list= array()) {
	$path = dir_path($path);
	$files = glob($path.'*');
	foreach($files as $v) {
		$fileext = fileext($v);
		if (!$exts || preg_match("/\.($exts)/i", $v)) {
			$list[] = $v;
			if (is_dir($v)) {
				$list = dir_list($v, $exts, $list);
			}
		}
	}
	return $list;
}
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function  sql_split($sql,$tablepre) {

	if($tablepre != "Es_") $sql = str_replace("Es_", $tablepre, $sql);
	//$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8",$sql);
	
	if($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql);
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query)
	{
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		$queries = array_filter($queries);
		foreach($queries as $query)
		{
			$str1 = substr($query, 0, 1);
			if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
		}
		$num++;
	}
	return $ret;
}
?>